package org.jetlinks.pro.koudai.Services;

import org.apache.commons.collections4.CollectionUtils;
import org.hswebframework.web.api.crud.entity.PagerResult;
import org.hswebframework.web.api.crud.entity.QueryParamEntity;
import org.hswebframework.web.crud.service.GenericReactiveCacheSupportCrudService;
import org.jetlinks.pro.koudai.entity.CourseEntity;
import org.jetlinks.pro.koudai.entity.CourseInfo;
import org.jetlinks.pro.koudai.entity.CourseTypeEntity;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 固件管理服务类,用于对设备固件信息进行增删改查
 *
 * @author zhouhao
 * @see GenericReactiveCacheSupportCrudService
 * @since 1.4
 */
@Service
public class CourseService extends GenericReactiveCacheSupportCrudService<CourseEntity, String> {

    private final CourseTypeService courseTypeService;

    public CourseService(CourseTypeService courseTypeService) {
        this.courseTypeService = courseTypeService;
    }

    public Mono<CourseInfo> getCourseInfo(String courseId) {
        CourseInfo courseInfo = new CourseInfo();
        return this
            .findById(courseId)
            .flatMap(courseEntity -> courseTypeService
                .findById(courseEntity.getCourseTypeId())
                .flatMap(courseInfo.with(courseEntity)::with));
    }

    //分页查询设备详情列表
    public Mono<PagerResult<CourseInfo>> queryCourseInfo(QueryParamEntity entity) {

        return this
            .queryPager(entity)
            .filter(e -> !e.getData().isEmpty())
            .flatMap(result ->
                convertCourseInfo(result.getData())
                    .collectList()
                    .map(detailList -> PagerResult.of(result.getTotal(), detailList, entity)))
            .defaultIfEmpty(PagerResult.empty());
    }

    private Flux<CourseInfo> convertCourseInfo(List<CourseEntity> instanceList) {
        if (CollectionUtils.isEmpty(instanceList)) {
            return Flux.empty();
        }
        return Flux.fromIterable(instanceList)
            .flatMap(courseEntity -> {
                CourseInfo courseInfo = new CourseInfo();
                return courseTypeService
                    .findById(courseEntity.getCourseTypeId())
                    .flatMap(courseInfo.with(courseEntity)::with);
            });
    }
}
